<?php

declare(strict_types=1);

namespace App\CustHub\Service;

use App\CustHub\Mapper\ChRobotApplyMapper;
use App\CustHub\Mapper\ChRobotMapper;
use App\CustHub\Model\ChRobotApplyLog;
use App\CustHub\Model\ChRobotApplyLogDetail;
use Hyperf\DbConnection\Db;
use Mine\Abstracts\AbstractService;
use Hyperf\Di\Annotation\Inject;

class ChRobotApplyService extends AbstractService
{
    #[Inject]
    protected ChSendConfigService $sendService;

    #[Inject]
    protected ChRobotMapper $chRobotMapper;

    public $mapper;

    public function __construct(ChRobotApplyMapper $mapper)
    {
        $this->mapper = $mapper;
    }

    /**
     * 查询某个机器人某个类型绑定的应用id
     * @param $targetType
     * @param $targetId
     * @return \Hyperf\Collection\Collection
     */
    public function getApplyTargetIds($targetType,$robotId)
    {
        return $this -> mapper -> model::query() -> where('target_type',$targetType) -> where('robot_id',$robotId) -> pluck('target_id');
    }

    public function getApplyTargetOnlineIds($targetType,$robotId)
    {
        return $this -> mapper -> model::query() -> where('target_type',$targetType) -> where('robot_id',$robotId) -> where('status',1) -> pluck('target_id');
    }

    /**
     * 查询应用机器人
     * @param $targetType
     * @param $targetId
     * @return \Hyperf\Collection\Collection
     */
    public function getApplyRobot($targetType,$targetId)
    {
        return $this -> mapper -> model::query() -> where('target_type',$targetType) -> where('target_id',$targetId) -> pluck('robot_id');
    }

    /**
     * 查询应用机器人信息
     * @param $targetType
     * @param $targetId
     * @return \Hyperf\Collection\Collection
     */
    public function getApplyRobotsInfo($targetType,$targetId)
    {
        return $this -> mapper -> model::query() -> with(['robot' => function($q){
            $q -> select(['nickname','id','avatar','corp_name','corp_id']);
        }]) -> where('target_type',$targetType) -> where('target_id',$targetId) -> select('robot_id','status','updated_at')-> get();
    }

    /**
     * 绑定应用
     * @param $targetType
     * @param $targetId
     * @param $robotId
     */
    public function robotApply($corpId,$targetType,$targetId,$robotId)
    {
        $this->mapper -> model::query() -> updateOrCreate(['corp_id' => $corpId,'robot_id' => $robotId,'target_id'=>$targetId,'target_type' => $targetType]);
    }

    /**
     * 批量取消应用
     * @param $targetType
     * @param $targetId
     * @param $robotId
     */
    public function robotBatchCancelApply($corpId, $targetType, $targetId, $robotIds)
    {
        $this->mapper -> model::query() ->where('corp_id',$corpId)-> where('target_type',$targetType)->where('target_id',$targetId)->whereIn('robot_id',$robotIds)->delete();
    }

    /**
     * 批量开启应用
     * @param $targetType
     * @param $targetId
     * @param $robotId
     */
    public function robotBatchOpenApply($corpId, $targetType, $targetId, $robotIds)
    {
        $this->mapper -> model::query() ->where('corp_id',$corpId)-> where('target_type',$targetType)->where('target_id',$targetId)->whereIn('robot_id',$robotIds)->update(['status'=>1]);
    }

    /**
     * 批量关闭应用
     * @param $targetType
     * @param $targetId
     * @param $robotId
     */
    public function robotBatchCloseApply($corpId, $targetType, $targetId, $robotIds)
    {
        $this->mapper -> model::query() ->where('corp_id',$corpId)-> where('target_type',$targetType)->where('target_id',$targetId)->whereIn('robot_id',$robotIds)->update(['status'=>0]);
    }

    /**
     * 批量绑定应用
     * @param $targetType
     * @param $targetIds
     * @param $robotIds
     * @return bool
     */
    public function batchApply($corpId,$targetType,$targetIds,$robotIds,$log = true)
    {
        Db::transaction(function() use($corpId,$targetType,$targetIds,$robotIds,$log){
             $model = ChRobotApplyLog::query() -> create(['corp_id' => $corpId,'target_type' => $targetType]);
            foreach ($targetIds as $targetId){
                $newRobotIds = [];
                foreach ($robotIds as $robotId){
                    $robotInfo=$this->chRobotMapper->findById($robotId);
                    if(empty($robotInfo)) continue;
                    $newRobotIds[] = $robotId;
                    $this -> robotApply($robotInfo->corp_id,$targetType,$targetId,$robotId);
                    //记录日志
                    $log &&  ChRobotApplyLogDetail::query()  -> create(['robot_id' => $robotId,'target_id' => $targetId,'log_id' => $model -> id]);
                }
                //删除多余的应用数据
                $this->mapper -> model::query() ->  where('target_type',$targetType) -> where('target_id',$targetId) -> whereNotIn('robot_id',$newRobotIds) -> delete();
            }
        });

    }


    /**
     * @param $class
     * @param $queryType  1查询机器人应用记录   2查询方案应用记录
     * 获取应用日志
     */
    public function getApplyLog($tableName,$targetType,$corpId,$queryType,$id=0)
    {
        if($queryType == 2){
            $result = Db::table('ch_robot_apply_log as al')
                -> leftJoin('ch_robot_apply_log_detail as ald','al.id','=','ald.log_id')
                -> leftJoin($tableName.' as t','t.id','=','ald.target_id')
                -> select([DB::raw('MAX(al.created_at) as created_at'),DB::raw('GROUP_CONCAT(DISTINCT t.id) as ids'), DB::raw('GROUP_CONCAT(DISTINCT t.title) as names')])
                -> groupBy('ald.log_id')
                -> where('al.target_type',$targetType)
                -> when(!empty($id),function ($query) use ($id){
                    $query->where('ald.target_id','like',$id);
                })
                -> get();
        }else{
            $result  = Db::table('ch_robot_apply_log as al')
                -> leftJoin('ch_robot_apply_log_detail as ald','al.id','=','ald.log_id')
                -> leftJoin('ch_robot as t','t.id','=','ald.robot_id')
                -> select([DB::raw('MAX(al.created_at) as created_at'),DB::raw('GROUP_CONCAT(DISTINCT t.id) as ids'), DB::raw('GROUP_CONCAT(DISTINCT t.nickname) as names')])
                -> where('al.corp_id',$corpId)
                -> where('al.target_type',$targetType)
                -> when(!empty($id),function ($query) use ($id){
                    $query->where('ald.target_id','like',$id);
                })
                -> groupBy('ald.log_id')
                -> get();
        }

        return $result;

    }

}